﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
public class CompilerMainWindow : EditorWindow
{
    //TODO 改为根据语言自动创建对应的GUI系统
    private SharpScriptSelector m_selector;
    private SharpCompilerSetting m_settingBar;

    [MenuItem("Window/C# Compiler")]
    public static void OpenCompilerWindow()
    {
        CompilerMainWindow window = EditorWindow.GetWindow<CompilerMainWindow>(true, "C# Compiler");

    }

    private void OnEnable()
    {

        m_selector = new SharpScriptSelector();
        m_selector.SearchScripts(Application.dataPath, true, null);

        m_settingBar = new SharpCompilerSetting();
    }


    private void OnGUI()
    {
        m_settingBar.Draw();
        m_selector.DrawElements();

        if (GUILayout.Button("Build Code!"))
        {
            DoBuild();
        }
    }


    private void Update()
    {



    }


    private bool m_isBuilding = false;
    private void DoBuild()
    {
        if (m_isBuilding)
        {
            Debug.Log("已经在生成");
            return;
        }
        m_isBuilding = true;
        string tempFolderPath = Application.dataPath.Substring(0,Application.dataPath.LastIndexOf(Path.AltDirectorySeparatorChar)) + @"\sharpBuildTemp";
        Debug.Log("Temp: "+tempFolderPath);
        List<string> m_allFiles = m_selector.GetAllSelectedFiles();
        //1.Copy Files 

        //  1.1.Clean Temp
        if (Directory.Exists(tempFolderPath))
        {
            

            Directory.Delete(tempFolderPath,true);
        }
        Directory.CreateDirectory(tempFolderPath);
        List<string> codeFiles = new List<string>();
        foreach (var script in m_allFiles)
        {
            string newFilePath = tempFolderPath + @"\" + Path.GetFileName(script);
            codeFiles.Add(newFilePath);
            File.Copy(script, newFilePath);
        }
        Debug.Log("Copy Done");
        //2.Validate Settings
        string define = m_settingBar.ScriptDefines;
        string outDll = m_settingBar.ExportPath + @"\" + m_settingBar.DllName+".dll";
        if (string.IsNullOrEmpty(m_settingBar.ExportPath)|| string.IsNullOrEmpty(m_settingBar.DllName))
        {
            EditorUtility.DisplayDialog("生成失败!", "导出路径和Dll名称都不能为空", "确定");
            return;
        }
        //3.Build Code
        var compiler = CompilerFactory.GetCompiler(CompilerDefines.dotNet35Compiler);
        if (null==compiler)
        {
            EditorUtility.DisplayDialog("生成失败","目标平台不正确 未找到对应的编译器","确定");
        }
        compiler.BuildCode(codeFiles, define, outDll,tempFolderPath);
    }
}



